# -*- coding: utf-8 -*-

from flask import request, abort
from google.appengine.ext import db
from dicthash.utils import project2dict
from dicthash.decorators import html_it, json_it, glue_GET_POST

from ..backends.working.models import Lenta
from ..forms import LentaForm

__all__ = ['add_lenta', 'view_lenta', 'edit_lenta', 'delete_lenta']


LentaProperties = ['id', 'namespace',  'name', 'desc', 'noteCounter', 'owner_key']

def _lenta_key(lenta_id, namespace=None):
    return db.Key.from_path('Lenta', lenta_id, namespace=namespace)

def _fetch_lenta(lenta_id, namespace=None):
    """ """
    lenta = Lenta.get(db.Key.from_path('Lenta', lenta_id, namespace=namespace)) or abort(404)
    return lenta

def _proj(lenta):
    """ """
    return project2dict(lenta, LentaProperties)


def _add_lenta_GET():
    """ """
    return {}

def _add_lenta_POST():
    """
    Add new lenta.
    """
    form = LentaForm(request.form)
    if form.is_valid():
        lenta = Lenta.new(**form.cleaned_data)
        lenta.put()
        return dict(lenta=_proj(lenta))
    else:
        return dict(errors=form.errors, lenta=request.form)
    
add_lenta = html_it ('/lenta/lenta/add_lenta.html', '/lenta/lenta/add_lenta_ok.html') \
                                (glue_GET_POST(_add_lenta_GET, _add_lenta_POST))


def _info(lenta_id, namespace):
    """
    Get lenta from datastore.
    """
    lenta = _fetch_lenta(lenta_id, namespace)
    return dict(lenta=_proj(lenta)) 

info = html_it ('/lenta/lenta/lenta_info.html') (_info)
info_json = json_it () (_info)


def _edit_lenta_GET(lenta_id):
    """ """
    return dict(lenta=_proj(_fetch_lenta(lenta_id)))

def _edit_lenta_POST(lenta_id):
    """ """
    lenta = _fetch_lenta(lenta_id)
        
    form = LentaForm(request.form)
    if form.is_valid():
        lenta.update(**form.cleaned_data)
        return dict(lenta=_proj(lenta))
    else:
        return dict(errors=form.errors, lenta=request.form)
    
edit_lenta = html_it ('/lenta/lenta/edit_lenta.html', '/lenta/lenta/edit_lenta_ok.html') \
                                 (glue_GET_POST(_edit_lenta_GET, _edit_lenta_POST))


def _delete_lenta_GET(lenta_id):
    """ """
    return dict(lenta=_proj(_fetch_lenta(lenta_id)))

def _delete_lenta_POST(lenta_id):
    """ """
    lenta = _fetch_lenta(lenta_id)
    lenta.delete()
    return {}

delete_lenta = html_it ('/lenta/lenta/delete_lenta.html', '/lenta/lenta/delete_lenta_ok.html') \
                                (glue_GET_POST(_delete_lenta_GET, _delete_lenta_POST))
